import api from '@/utils/http.api.js'
import setting from '@/settings/projectSetting.js'
import { storage } from '@/utils/storage'
import util from '@/utils/util'
import { GLOB_OPENID, GLOB_SHARE_CODE, GLOB_MHM_ID, GLOB_MHM_STATE } from '@/store/mutation-types'
const { appTitle, appBaseUrl } = setting

export default {
  namespaced: true,
  state: {
    globalSwitch: null, // 全局开关
    globCartNumber: 0, // 购物车数量
    globConfigTypeset: null, // 排版配置
    globConfigInit: null, // 配置信息
    globNotifyUnread: 0, // 未读消息
    globSchoolState: storage.get(GLOB_MHM_STATE, 1), // 首次打开应用时主动跳转到切换机构页面
    globSchoolId: storage.get(GLOB_MHM_ID, 1), // 机构id
    globOpenid: storage.get(GLOB_OPENID, ''), // openid
    globShareCode: storage.get(GLOB_SHARE_CODE, ''), // 分享code
  },
  getters: {
    // 配置
    globConfigInit(state) {
      return state.globConfigInit
    },
    // 标题
    getGlobTitle(state) {
      let config = state.globConfigInit
      if (util.isDef(config)) {
        return config.site_info.title
      }
      return appTitle
    },
    // 注册开关
    getGlobRegisterSwitch(state) {
      let config = state.globConfigInit
      if (util.isDef(config)) {
        return config.open_reg
      }
      return 0
    },
    // 课程排版
    getGlobCourseTypeset(state) {
      let typeset = state.globConfigTypeset
      if (util.isDef(typeset)) {
        return typeset.course
      }
      return 0
    },
    // 个人中心排版
    getGlobProfileTypeset(state) {
      let typeset = state.globConfigTypeset
      if (util.isDef(typeset)) {
        return typeset.profile
      }
      return 0
    },
    // 课程笔记开关
    getGlobCourseNoteSwitch(state) {
      let switchData = state.globalSwitch
      if (util.isDef(switchData)) {
        return switchData.note
      }
      return 0
    },
    // 课程评论开关
    getGlobCourseCommentSwitch(state) {
      let switchData = state.globalSwitch
      if (util.isDef(switchData)) {
        return switchData.comment
      }
      return 0
    },
    // 独立机构开关
    getGlobSchoolSwitch(state) {
      let switchData = state.globalSwitch
      if (util.isDef(switchData)) {
        return switchData.school_app
      }
      return 0
    },
    // 课程课件
    getGlobCoursewareSwitch(state) {
      let switchData = state.globalSwitch
      if (util.isDef(switchData)) {
        return switchData.courseware
      }
      return 0
    },
    // 课程考试
    getGlobCourseExamSwitch(state) {
      let switchData = state.globalSwitch
      if (util.isDef(switchData)) {
        return switchData.exam
      }
      return 0
    },
    // 登录配置
    getGlobLoginConfig(state) {
      let config = state.globConfigInit
      if (util.isDef(config)) {
        return config.login_config
      }
      return {}
    },
    // 状态栏高度
    globStatusBarHeight() {
      let systemInfo = uni.$u.sys()
      return systemInfo.statusBarHeight
    },
    // 导航高度
    globNavbarHeight() {
      let systemInfo = uni.$u.sys()
      let height = 0
      // #ifdef APP-PLUS || H5
      height = 44
      // #endif
      // #ifdef MP
      height = systemInfo.platform == 'ios' ? 44 : 48
      // #endif
      return height
    },
    // 窗口高度
    globWindowHeight() {
      let systemInfo = uni.$u.sys()
      return systemInfo.windowHeight
    },
    // 窗口宽度
    globWindowWidth() {
      let systemInfo = uni.$u.sys()
      return systemInfo.windowWidth
    },
    // 导航右边胶囊的宽度
    globNavbarRightButtonWidth(state, getters) {
      let rightButtonWidth = 0
      // 获取系统状态栏的高度
      let menuButtonInfo = {}
      // 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
      // #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
      menuButtonInfo = uni.getMenuButtonBoundingClientRect()
      // #endif
      // #ifdef MP
      rightButtonWidth = getters.globWindowWidth - menuButtonInfo.left
      // #endif
      return rightButtonWidth
    },
    // 协议标题
    getAgreementTitle: (state) => (key) => {
      if (util.isDef(state.globConfigInit)) {
        const list = state.globConfigInit.content_conf
        const data = list.find((item) => item.key === key)
        return data ? data.title : ''
      }
      return ''
    },
  },
  mutations: {
    setConfigInit(state, data) {
      state.globConfigInit = data
    },
    setSchoolId(state, value) {
      state.globSchoolId = value
      storage.set(GLOB_MHM_ID, value)
    },
    setSchoolState(state, value) {
      state.globSchoolState = value
      storage.set(GLOB_MHM_STATE, value)
    },
    comGlobSwitch(state, data) {
      state.globalSwitch = data
    },
    comGlobCartNumber(state, data) {
      state.globCartNumber = data
    },
    comGlobNotifyUnread(state, data) {
      state.globNotifyUnread = data
    },
    comGlobConfigTypeset(state, data) {
      state.globConfigTypeset = data
    },
    comGlobConfigopenid(state, openid) {
      state.globOpenid = openid
      storage.set(GLOB_OPENID, openid)
    },
    setShareCode(state, value) {
      state.globShareCode = value
      storage.set(GLOB_SHARE_CODE, value)
    },
  },
  actions: {
    setGlobConfigMhmid({ commit }, id) {
      commit('setSchoolId', id)
    },
    setGlobConfigInit({ commit }) {
      api.getConfig().then((res) => {
        const { data } = res
        commit('setConfigInit', data)
        commit('designSetting/setGlobAppTheme', data.theme_color, {
          root: true,
        })
        // #ifdef H5
        // 统计
        /* if (data.site_info.stats_code) {
          let stats_code = document.createElement('script')
          stats_code.src = data.site_info.stats_code
          document.body.appendChild(stats_code)
        } */

        // 主题
        window.document.documentElement.setAttribute('data-theme', data.theme_color)
        // #endif
      })
    },
    setGlobSwitch({ commit }) {
      api.getSwitch().then((res) => {
        const { data } = res
        commit('comGlobSwitch', data)
      })
    },
    setGlobCartNumber({ commit }) {
      api.getCartNum().then((res) => {
        const { data } = res
        commit('comGlobCartNumber', data)
      })
    },
    // 未读消息
    setGlobNotifyUnread({ commit }) {
      api.getUserNotifyUnread().then((res) => {
        const { data } = res
        commit('comGlobNotifyUnread', data)
      })
    },
    setGlobConfigTypeset({ commit }) {
      api.getConfigTypeset().then((res) => {
        const { data } = res
        commit('comGlobConfigTypeset', data)
      })
    },
    setGlobConfigOpenid({ commit }, openid) {
      commit('comGlobConfigopenid', openid)
    },
    setGlobWeixinAppid({ commit, state }) {
      if (!state.globOpenid) {
        // #ifdef H5
        if (util.isWechat()) {
          api.getPayWxappid().then((res) => {
            const { data } = res
            let loc_href = appBaseUrl + '/pageUser/setting/wechatLogin'
            let href = encodeURIComponent(loc_href)
            document.location.replace(
              `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${data}&redirect_uri=${href}&response_type=code&scope=snsapi_userinfo&state=openid#wechat_redirect`
            )
          })
        }
        // #endif
        // #ifdef MP-WEIXIN
        uni.login({
          provider: 'weixin',
          onlyAuthorize: true, // 微信登录仅请求授权认证
          success: (loginRes) => {
            api
              .getConfigOpenid({
                code: loginRes.code,
              })
              .then((res) => {
                const { data } = res
                commit('comGlobConfigopenid', data)
              })
              .catch((err) => {
                console.log(err)
              })
          },
        })
        // #endif
      }
    },
    // 更新全局信息
    globUpdateInit({ commit }) {
      uni.$u.debounce(
        () => {
          api.getConfigSdn().then((res) => {
            // 机构id
            commit('setSchoolId', res.data.mhm_id)

            // 初始化配置
            api.getConfig().then((res) => {
              const { data } = res
              commit('setConfigInit', data)
              commit('designSetting/setGlobAppTheme', data.theme_color, {
                root: true,
              })
              // #ifdef H5
              // 主题
              window.document.documentElement.setAttribute('data-theme', data.theme_color)
              // #endif
            })

            // 排版配置
            api.getConfigTypeset().then((res) => {
              const { data } = res
              commit('comGlobConfigTypeset', data)
            })

            // 开关配置
            api.getSwitch().then((res) => {
              const { data } = res
              commit('comGlobSwitch', data)
            })
          })
        },
        1000,
        true
      )
    },
  },
}
